<template>
  <div>
    <h5 class="text-lg my-3">"{{ title }}"的搜索相关结果</h5>

    <UiTab>
      <UiTabItem
        :active="item.value === route.params.type"
        v-for="(item, index) in tabs"
        :key="index"
        @click="handleClick(item.value)"
        >{{ item.label }}</UiTabItem
      >
    </UiTab>

    <LoadingGroup :pending="pending" :error="error" :is-empty="rows.length === 0">
      <template #loading>
        <LoadingCourseSkeleton />
      </template>

      <n-grid x-gap="12" :cols="4">
        <n-gi v-for="(item, index) in rows" :key="index">
          <CourseList :item="item" />
        </n-gi>
      </n-grid>

      <div class="flex justify-center items-center mt-5 mb-10">
        <n-pagination
          size="large"
          :page="page"
          :item-count="total"
          :page-size="limit"
          :on-update:page="handlePageChange"
        />
      </div>
    </LoadingGroup>
  </div>
</template>

<script setup>
// 引入CompositionAPI
import { ref, computed, watch } from "vue";

// naive-ui
import { NGrid, NGi, NPagination } from "naive-ui";

// 路由实例
const route = useRoute();

// 获取关键词
const title = ref(route.query.keyword);

// 获取类型
const type = ref(route.params.type);

// 中间件
definePageMeta({
  middleware: ["search"],
});

// 导航栏标题
useHead({ title: title.value });

// 导航栏列表
const tabs = [
  {
    label: "课堂",
    value: "course",
  },
  {
    label: "专栏",
    value: "column",
  },
];

// 点击导航栏事件
const handleClick = (t) => {
  navigateTo({
    params: {
      ...route.params,
      type: t,
      page: 1,
    },
    query: {
      ...route.query,
    },
  });
};

const {
  page,
  limit,
  total,
  rows,
  handlePageChange,
  pending,
  error,
  refresh,
} = await usePage(({ page, limit }) =>
  useSearchListApi(() => {
    return {
      page: page,
      keyword: encodeURIComponent(title.value),
      type: type.value,
    };
  })
);

// 监听
const stop = watch(
  () => route.query.keyword,
  (newVal) => {
    title.value = newVal;
    refresh();
  }
);

// 结束页面
onBeforeUnmount(() => stop());
</script>
